import React, { Component } from "react";
import LazyLoad from "react-lazy-load";
import { withStyles } from "@material-ui/core";
import { get } from "lodash";
import copRegServerRestProvider from "../../dataprovider/ra-data-copRegServer-rest";

const styles = {
    img: {
        objectFit: "cover",
        width: "100%",
        height: "100%",
    },
};

class ImageField extends Component {
    constructor(props) {
        super(props);
        this.state = { image: "" };
    }

    async componentDidMount() {
        const {
            record, source, width, height, history,
        } = this.props;
        const url = get(record, source);
        if (/^https?/.test(url)) this.setState({ image: url });
        else {
            copRegServerRestProvider("DOWNLOAD", "images", { url, width, height })
                .then(async (res) => {
                    const imageBlob = await res.blob();
                    this.setState({ image: URL.createObjectURL(imageBlob) });
                    return 0;
                }).catch((e) => {
                    const { status } = e;
                    if (status === 401 || status === 403) {
                        // eslint-disable-next-line no-undef
                        localStorage.removeItem("token");
                        history.push("/login");
                    }
                });
        }
    }

    render() {
        const { image } = this.state;
        const { width, height, classes } = this.props;
        return (
            <LazyLoad
                width={width}
                height={height}
                offset={200}
            >
                <img
                    src={image}
                    loading="lazy"
                    title={this.props.record.image.name}
                    className={classes.img}
                />
            </LazyLoad>
        );
    }
}

export default withStyles(styles)(ImageField);
